const { ipcRenderer } = require('electron');

// 配置
let settings = {
    opacity: 0.9,
    width: 400,
    height: 600,
    alwaysOnTop: true,
    refreshInterval: 2000,
    locked: false,
    // UI 个性化设置（仅前端存储）
    fontSize: parseInt(localStorage.getItem('overlay_fontSize') || '12', 10),
    themeColor: localStorage.getItem('overlay_themeColor') || '#e7ae97',
    compactMode: localStorage.getItem('overlay_compact') === '1',
    themeMode: localStorage.getItem('overlay_themeMode') || 'dark'
};

// 排序和显示设置
let displaySettings = {
    sortBy: 'damage', // damage, healing, taken, dps, hps, profession
    showDamage: true,
    showHealing: true,
    showTaken: true,
    showProfession: true
};

let refreshTimer = null;
let lastButtonCount = 0; // 追踪按钮数量变化
let updatePaused = false; // 暂停更新标志

// 计时器相关变量
let timerState = {
    isRunning: false,
    duration: 60,
    timeLeft: 60,
    startTime: null,
    timerInterval: null,
    initialData: null
};

// 全局技能点击处理函数
window.handleSkillClick = function(uid) {
    console.log('🎯 全局技能点击函数被调用，UID:', uid);
    if (settings.locked) {
        console.log('窗口已锁定，无法点击');
        alert('窗口已锁定，请先解锁后再操作');
        return;
    }
    
    const button = document.querySelector(`.skill-btn[data-uid="${uid}"]`);
    if (!button) {
        console.log('未找到对应的按钮元素');
        return;
    }
    
    console.log('调用togglePlayerSkillDetails，UID:', uid);
    togglePlayerSkillDetails(uid, button);
};

// 初始化应用
async function init() {
    try {
        // 获取当前设置（与本地UI个性化设置合并）
        const nativeSettings = await ipcRenderer.invoke('get-settings');
        settings = { ...settings, ...nativeSettings };
        updateSettingsUI();
        
        // 绑定事件
        bindEvents();
        
        // 验证事件委托绑定
        console.log('🔍 验证事件委托绑定状态:');
        console.log('  - handleGlobalClick函数:', typeof handleGlobalClick);
        console.log('  - 全局点击事件监听器:', document.onclick ? '已绑定' : '未绑定');
        
        // 开始数据更新
        initSortFromMenu();
        startDataRefresh();
        
        console.log('✅ 悬浮窗初始化完成');
    } catch (error) {
        console.error('初始化失败:', error);
        showError('初始化失败: ' + error.message);
    }
}

// 使用原生XMLHttpRequest替代fetch
function fetchData(url) {
    return new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', url);
        xhr.onload = function() {
            if (xhr.status >= 200 && xhr.status < 300) {
                try {
                    const data = JSON.parse(xhr.responseText);
                    resolve(data);
                } catch (e) {
                    reject(new Error('Invalid JSON response'));
                }
            } else {
                reject(new Error(`HTTP ${xhr.status}: ${xhr.statusText}`));
            }
        };
        xhr.onerror = function() {
            reject(new Error('Network error'));
        };
        xhr.timeout = 5000; // 5秒超时
        xhr.ontimeout = function() {
            reject(new Error('Request timeout'));
        };
        xhr.send();
    });
}

// 技能按钮点击处理
function handleSkillButtonClick(uid) {
    console.log('🎯 处理技能按钮点击，UID:', uid);
    if (settings.locked) {
        console.log('窗口已锁定，无法点击');
        alert('窗口已锁定，请先解锁后再操作');
        return;
    }
    
    const button = document.querySelector(`.skill-btn[data-uid="${uid}"]`);
    if (!button) {
        console.log('未找到对应的按钮元素');
        return;
    }
    
    console.log('调用togglePlayerSkillDetails，UID:', uid);
    togglePlayerSkillDetails(uid, button);
}

// 昵称编辑处理
function handleEditNickname(uid, currentNickname) {
    console.log('🎯 处理昵称编辑，UID:', uid, '当前昵称:', currentNickname);
    // 复用内置的昵称编辑弹窗，避免重复ID冲突
    currentEditingPlayerUid = uid;
    const modal = document.getElementById('nicknameEditModal');
    const uidElement = document.getElementById('editingPlayerUid');
    const nicknameInput = document.getElementById('nicknameInput');
    if (!modal || !uidElement || !nicknameInput) return;
    uidElement.textContent = uid;
    nicknameInput.value = currentNickname || '';
    modal.classList.remove('hidden');
    nicknameInput.focus();
    nicknameInput.select();
}

// 昵称删除处理
function handleDeleteNickname(uid) {
    console.log('🎯 处理昵称删除，UID:', uid);
    if (confirm(`确定要删除玩家ID ${uid} 的昵称吗？`)) {
        saveNicknameInManager(uid, '').then(() => {
            delete allNicknames[uid];
            filterNicknames();
            updateDisplay();
        });
    }
}

// 昵称管理处理
function handleManageNicknames() {
    console.log('🎯 处理昵称管理');
    showNicknameManager();
}

// 关闭昵称管理
function handleCloseNicknameManager() {
    console.log('🎯 处理关闭昵称管理');
    hideNicknameManager();
}

// 添加昵称
function handleAddNickname() {
    console.log('🎯 处理添加昵称');
    showAddNicknameDialog();
}

// 刷新昵称
function handleRefreshNicknames() {
    console.log('🎯 处理刷新昵称');
    refreshNicknamesList();
}

// 全局点击处理函数
function handleGlobalClick(e) {
    console.log('🎯 全局点击事件触发:', e.target.tagName, e.target.className, e.target.id);
    console.log('🎯 目标元素:', e.target);
    console.log('🎯 目标元素的classList:', Array.from(e.target.classList));
    
    // 移除技能按钮点击逻辑（改为点击玩家条）
    
    // 处理昵称编辑按钮点击
    if (e.target.classList.contains('edit-nickname-item')) {
        e.preventDefault();
        e.stopPropagation();
        const uid = e.target.dataset.uid;
        const nickname = e.target.dataset.nickname;
        console.log('🎯 昵称编辑按钮被点击:', uid, nickname);
        handleEditNickname(uid, nickname);
        return;
    }
    
    // 处理昵称删除按钮点击
    if (e.target.classList.contains('delete-nickname-item')) {
        e.preventDefault();
        e.stopPropagation();
        const uid = e.target.dataset.uid;
        console.log('🎯 昵称删除按钮被点击:', uid);
        handleDeleteNickname(uid);
        return;
    }
    
    // 处理昵称管理按钮点击
    if (e.target.id === 'manageNicknames') {
        e.preventDefault();
        e.stopPropagation();
        console.log('🎯 昵称管理按钮被点击');
        handleManageNicknames();
        return;
    }
    
    // 处理昵称管理弹窗按钮
    if (e.target.id === 'closeNicknameManager') {
        e.preventDefault();
        e.stopPropagation();
        console.log('🎯 关闭昵称管理按钮被点击');
        handleCloseNicknameManager();
        return;
    }
    
    if (e.target.id === 'addNicknameBtn') {
        e.preventDefault();
        e.stopPropagation();
        console.log('🎯 添加昵称按钮被点击');
        handleAddNickname();
        return;
    }
    
    if (e.target.id === 'refreshNicknamesBtn') {
        e.preventDefault();
        e.stopPropagation();
        console.log('🎯 刷新昵称按钮被点击');
        handleRefreshNicknames();
        return;
    }
}

// 绑定事件
function bindEvents() {
    // 标题栏按钮
    const clearBtn = document.getElementById('clearBtn');
    if (clearBtn) clearBtn.addEventListener('click', clearServerDataAndUi);
    document.getElementById('lockBtn').addEventListener('click', toggleLock);
    document.getElementById('timerBtn').addEventListener('click', toggleTimer);
    document.getElementById('settingsBtn').addEventListener('click', toggleSettings);
    document.getElementById('minimizeBtn').addEventListener('click', minimizeWindow);
    document.getElementById('closeBtn').addEventListener('click', closeWindow);
    
    // 使用事件委托处理所有动态元素的点击
    document.addEventListener('click', handleGlobalClick);
    
    // 监听来自主进程的点击事件
    ipcRenderer.on('skill-button-click', (event, uid) => {
        console.log('收到主进程技能按钮点击事件:', uid);
        handleSkillButtonClick(uid);
    });

    // 全部玩家按钮
    const allBtn = document.getElementById('allBtn');
    if (allBtn) {
        allBtn.addEventListener('click', async () => {
            try {
                await ipcRenderer.invoke('open-all-players');
            } catch (e) {
                console.error('打开全部玩家窗口失败', e);
            }
        });
    }
    
    ipcRenderer.on('nickname-edit-click', (event, uid, nickname) => {
        console.log('收到主进程昵称编辑点击事件:', uid, nickname);
        handleEditNickname(uid, nickname);
    });
    
    ipcRenderer.on('nickname-delete-click', (event, uid) => {
        console.log('收到主进程昵称删除点击事件:', uid);
        handleDeleteNickname(uid);
    });
    
    // 事件委托已绑定，处理所有动态元素点击
    console.log('✅ 事件委托已绑定，处理所有动态元素点击');
    

    
    // 设置面板
    document.getElementById('closeSettings').addEventListener('click', hideSettings);
    
    // 设置控件
    document.getElementById('opacitySlider').addEventListener('input', updateOpacity);
    document.getElementById('widthInput').addEventListener('change', updateSize);
    document.getElementById('heightInput').addEventListener('change', updateSize);
    document.getElementById('alwaysOnTopCheck').addEventListener('change', updateAlwaysOnTop);
    document.getElementById('refreshInterval').addEventListener('change', updateRefreshInterval);
    document.getElementById('resetPosition').addEventListener('click', resetPosition);
    // 字体与主题
    const fontSizeInput = document.getElementById('fontSizeInput');
    const themeColorInput = document.getElementById('themeColorInput');
    if (fontSizeInput) fontSizeInput.addEventListener('change', updateFontSizeSetting);
    if (themeColorInput) themeColorInput.addEventListener('input', updateThemeColorSetting);
    const compactCheck = document.getElementById('compactModeCheck');
    if (compactCheck) compactCheck.addEventListener('change', updateCompactMode);
    document.querySelectorAll('input[name="themeMode"]').forEach(r => r.addEventListener('change', updateThemeMode));
    
    // 计时器事件
    document.getElementById('closeTimer').addEventListener('click', hideTimer);
    
    // 计时器预设按钮
    document.querySelectorAll('.timer-preset').forEach(btn => {
        btn.addEventListener('click', (e) => {
            const time = parseInt(e.target.dataset.time);
            setTimerDuration(time);
        });
    });
    
    // 自定义时间按钮
    document.getElementById('customStartBtn').addEventListener('click', () => {
        const time = parseInt(document.getElementById('customTime').value);
        if (time >= 10 && time <= 600) {
            setTimerDuration(time);
        } else {
            alert('请输入10-600秒之间的数值');
        }
    });
    
    // 计时器控制按钮
    document.getElementById('startTimerBtn').addEventListener('click', startTimer);
    document.getElementById('stopTimerBtn').addEventListener('click', stopTimer);
    document.getElementById('resetTimerBtn').addEventListener('click', resetTimer);
    document.getElementById('exitTimerBtn').addEventListener('click', exitTimerMode);
    
    // 下拉菜单控制
    const controlBtn = document.getElementById('controlBtn');
    const controlMenu = document.getElementById('controlMenu');
    
    controlBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        controlMenu.classList.toggle('show');
    });
    
    // 点击其他地方关闭下拉菜单
    document.addEventListener('click', (e) => {
        if (!e.target.closest('.control-dropdown')) {
            controlMenu.classList.remove('show');
        }
    });
    
    // 排序选项
    document.querySelectorAll('input[name="sortBy"]').forEach(radio => {
        radio.addEventListener('change', (e) => {
            if (e.target.checked) {
                setSortMode(e.target.value);
            }
        });
    });
    
    // 显示选项
    document.getElementById('showDamageDropdown').addEventListener('change', updateDisplaySettings);
    document.getElementById('showHealingDropdown').addEventListener('change', updateDisplaySettings);
    document.getElementById('showTakenDropdown').addEventListener('change', updateDisplaySettings);
    document.getElementById('showProfessionDropdown').addEventListener('change', updateDisplaySettings);
    
    // 返回按钮
    const backBtn = document.getElementById('backBtn');
    if (backBtn) backBtn.addEventListener('click', showMainView);
    
    // 昵称编辑功能
    const editNicknameBtn = document.getElementById('editNicknameBtn');
    const closeNicknameModalBtn = document.getElementById('closeNicknameModal');
    const cancelNicknameBtn = document.getElementById('cancelNicknameBtn');
    const saveNicknameBtn = document.getElementById('saveNicknameBtn');
    if (editNicknameBtn) {
        editNicknameBtn.onclick = (e) => { e.stopPropagation(); showNicknameEditModal(); };
    }
    if (closeNicknameModalBtn) closeNicknameModalBtn.onclick = hideNicknameEditModal;
    if (cancelNicknameBtn) cancelNicknameBtn.onclick = hideNicknameEditModal;
    if (saveNicknameBtn) saveNicknameBtn.onclick = savePlayerNickname;
    
    // 昵称管理功能
    const searchEl = document.getElementById('nicknameSearch');
    if (searchEl) searchEl.addEventListener('input', filterNicknames);
    const manageBtn = document.getElementById('manageNicknames');
    if (manageBtn) manageBtn.addEventListener('click', showNicknameManager);
    const closeManagerBtn = document.getElementById('closeNicknameManager');
    if (closeManagerBtn) closeManagerBtn.addEventListener('click', hideNicknameManager);
    const addNicknameBtn = document.getElementById('addNicknameBtn');
    if (addNicknameBtn) addNicknameBtn.addEventListener('click', showAddNicknameDialog);
    const refreshNicknamesBtn = document.getElementById('refreshNicknamesBtn');
    if (refreshNicknamesBtn) refreshNicknamesBtn.addEventListener('click', refreshNicknamesList);
}

// 获取伤害数据
async function fetchDamageData() {
    try {
        const data = await fetchData('http://localhost:8989/api/data');
        if (data.code !== 0) {
            throw new Error(data.msg || '服务器返回错误');
        }
        return data.user || {};
    } catch (error) {
        console.error('获取数据失败:', error);
        throw error;
    }
}

// 上次数据的哈希值，用于检测数据是否真的变化了
let lastDataHash = '';

// 更新显示数据
async function updateDisplay() {
    // 1) 恢复：当有技能详情展开时，暂停数据刷新，避免抖动
    if (document.querySelector('.damage-item.expanded .skill-details')) {
        //console.log('⏸ 技能详情展开中，暂停刷新');
        return;
    }
    
    const damageList = document.getElementById('damageList');
    
    try {
        const userData = await fetchDamageData();
        
        if (Object.keys(userData).length === 0) {
            damageList.innerHTML = '<div class="loading">📊 暂无数据</div>';
            lastDataHash = '';
            return;
        }
        
        // 检查数据是否真的变化了（防止无意义的DOM重建）
        const currentDataHash = JSON.stringify(userData);
        if (currentDataHash === lastDataHash) {
            console.log('📊 数据未变化，跳过更新');
            return;
        }
        lastDataHash = currentDataHash;
        
        // 转换为数组并排序
        const players = Object.keys(userData).map(uid => ({
            uid: uid,
            nickname: userData[uid].nickname || userData[uid].name || `玩家_${uid}`,
            ...userData[uid]
        }));
        
        console.log('📊 数据已变化，开始更新 - 玩家数量:', players.length);
        
        // 根据当前排序模式排序
        sortPlayers(players);
        
        // 计算百分比（第一名为100%），根据当前排序类型确定最大值
        let maxValue = 1;
        if (players.length > 0) {
            switch (displaySettings.sortBy) {
                case 'damage':
                    maxValue = players[0].total_damage.total;
                    break;
                case 'healing':
                    maxValue = (players[0].total_healing && players[0].total_healing.total) || 1;
                    break;
                case 'taken':
                    maxValue = players[0].taken_damage || 1;
                    break;
                case 'dps':
                    maxValue = players[0].total_dps || 1;
                    break;
                case 'hps':
                    maxValue = players[0].total_hps || 1;
                    break;
                default:
                    maxValue = players[0].total_damage.total;
                    break;
            }
        }
        
        // 增加玩家条高度后，默认展示数量适当提升，仍给紧凑模式更多可视数量
        const maxVisible = settings.compactMode ? 7 : 6;
        const visiblePlayers = players.slice(0, maxVisible);
        
        // 总览柱状图更新
        updateOverviewBars(userData);

        // 先清空列表
        damageList.innerHTML = '';
        
        // 使用DOM操作而不是innerHTML（可能解决Electron问题）
        visiblePlayers.forEach((player, index) => {
            const rank = index + 1;
            
            // 根据当前排序类型计算百分比
            let currentValue = 0;
            let percentage = 0;
            switch (displaySettings.sortBy) {
                case 'damage':
                    currentValue = player.total_damage.total;
                    break;
                case 'healing':
                    currentValue = (player.total_healing && player.total_healing.total) || 0;
                    break;
                case 'taken':
                    currentValue = player.taken_damage || 0;
                    break;
                case 'dps':
                    currentValue = player.total_dps || 0;
                    break;
                case 'hps':
                    currentValue = player.total_hps || 0;
                    break;
                default:
                    currentValue = player.total_damage.total;
                    break;
            }
            percentage = maxValue > 0 ? Math.round((currentValue / maxValue) * 100) : 0;
            const critRate = ((player.total_count.critical / player.total_count.total) * 100).toFixed(1);
            const luckyRate = ((player.total_count.lucky / player.total_count.total) * 100).toFixed(1);
            
            // 获取职业信息
            const profession = player.profession || '未知';
            
            // 处理治疗数据（如果有）
            const hasHealing = player.total_healing && player.total_healing.total > 0;
            const healingData = hasHealing ? player.total_healing : null;
            const healingDps = hasHealing ? (player.total_hps || 0).toFixed(0) : '0';
            
            // 处理承受伤害（如果有）
            const takenDamage = player.taken_damage || 0;
            
            const rankClass = rank <= 3 ? `rank-${rank}` : '';
            
            // 创建玩家项目DOM元素
            const damageItem = document.createElement('div');
            damageItem.className = `damage-item ${rankClass}`;
            damageItem.setAttribute('data-uid', player.uid);
            
            // 创建玩家信息 - 使用网格布局固定对齐
            const playerInfo = document.createElement('div');
            playerInfo.className = 'player-info compact';
            
            // 1. 玩家名称 (第1列，自适应宽度)
            const playerName = document.createElement('div');
            playerName.className = 'player-name';
            playerName.textContent = player.nickname;
            playerInfo.appendChild(playerName);
            
            // 2. 职业信息 (第2列，固定宽度)
            if (displaySettings.showProfession) {
                const playerProfession = document.createElement('div');
                playerProfession.className = 'player-profession';
                // 职业彩色标签：根据主要贡献染色
                let tagColor = '#95a5a6';
                const dmg = player.total_damage?.total || 0;
                const heal = player.total_healing?.total || 0;
                const taken = player.taken_damage || 0;
                if (dmg >= heal && dmg >= taken) tagColor = '#e74c3c';
                else if (heal >= dmg && heal >= taken) tagColor = '#2ecc71';
                else tagColor = '#7f8c8d';
                playerProfession.style.cssText = `padding:2px 6px;border-radius:10px;border:1px solid ${tagColor};color:${tagColor};font-size:10px;white-space:nowrap;`;
                playerProfession.textContent = profession;
                playerInfo.appendChild(playerProfession);
            } else {
                // 即使不显示职业，也要添加空div保持网格对齐
                const emptyDiv = document.createElement('div');
                playerInfo.appendChild(emptyDiv);
            }
            
            // 3. 排行标签 (第3列，固定宽度)
            const rankBadge = document.createElement('div');
            rankBadge.className = 'rank-badge';
            rankBadge.style.cssText = 'white-space: nowrap;';
            rankBadge.textContent = `#${rank}`;
            playerInfo.appendChild(rankBadge);
            
            // 4. 百分比显示 (第4列，固定宽度)
            const mainPercentage = document.createElement('div');
            mainPercentage.className = 'main-percentage';
            mainPercentage.style.cssText = 'color: #f39c12; font-weight: bold; font-size: 12px; white-space: nowrap; text-align: right;';
            mainPercentage.textContent = `${percentage}%`;
            playerInfo.appendChild(mainPercentage);
            
            damageItem.appendChild(playerInfo);
            
            // 创建伤害主要信息
            const damageMain = document.createElement('div');
            damageMain.className = 'damage-main';
            
            // 根据排序类型显示主要数据行 + 统计芯片行
            const mainStatRow = document.createElement('div');
            mainStatRow.className = 'stat-row main-stat';
            
            switch (displaySettings.sortBy) {
                case 'damage':
                    if (displaySettings.showDamage) {
                        mainStatRow.innerHTML = `
                            <span class="stat-label">总伤害:</span>
                            <span class="stat-value">${formatNumber(player.total_damage.total)}</span>
                        `;
                        damageMain.appendChild(mainStatRow);
                    }
                    break;
                case 'healing':
                    if (displaySettings.showHealing && hasHealing) {
                        mainStatRow.className = 'stat-row main-stat healing';
                        mainStatRow.innerHTML = `
                            <span class="stat-label">总治疗:</span>
                            <span class="stat-value healing-value">${formatNumber(healingData.total)}</span>
                        `;
                        damageMain.appendChild(mainStatRow);
                    }
                    break;
                case 'taken':
                    if (displaySettings.showTaken && takenDamage > 0) {
                        mainStatRow.className = 'stat-row main-stat taken';
                        mainStatRow.innerHTML = `
                            <span class="stat-label">总承伤:</span>
                            <span class="stat-value taken-value">${formatNumber(takenDamage)}</span>
                        `;
                        damageMain.appendChild(mainStatRow);
                    }
                    break;
                case 'dps':
                    mainStatRow.innerHTML = `
                        <span class="stat-label">DPS:</span>
                        <span class="stat-value">${player.total_dps.toFixed(0)}</span>
                    `;
                    damageMain.appendChild(mainStatRow);
                    break;
                case 'hps':
                    if (hasHealing) {
                        mainStatRow.className = 'stat-row main-stat healing';
                        mainStatRow.innerHTML = `
                            <span class="stat-label">HPS:</span>
                            <span class="stat-value healing-value">${healingDps}</span>
                        `;
                        damageMain.appendChild(mainStatRow);
                    }
                    break;
                default:
                    if (displaySettings.showDamage) {
                        mainStatRow.innerHTML = `
                            <span class="stat-label">总伤害:</span>
                            <span class="stat-value">${formatNumber(player.total_damage.total)}</span>
                        `;
                        damageMain.appendChild(mainStatRow);
                    }
                    break;
            }
            
            // 统计芯片（不增加高度，横向一行展示三项）
            const chips = document.createElement('div');
            chips.className = 'stat-chips';
            const dmgChip = document.createElement('span');
            dmgChip.className = 'chip damage';
            dmgChip.textContent = `伤害 ${formatNumber(player.total_damage.total)}`;
            chips.appendChild(dmgChip);
            if (displaySettings.showHealing && hasHealing) {
                const healChip = document.createElement('span');
                healChip.className = 'chip healing';
                healChip.textContent = `治疗 ${formatNumber(healingData.total)}`;
                chips.appendChild(healChip);
            }
            if (displaySettings.showTaken && takenDamage > 0) {
                const takenChip = document.createElement('span');
                takenChip.className = 'chip taken';
                takenChip.textContent = `承伤 ${formatNumber(takenDamage)}`;
                chips.appendChild(takenChip);
            }
            damageMain.appendChild(chips);
            
            const percentageBar = document.createElement('div');
            percentageBar.className = 'percentage-bar';
            
            // 根据排序类型设置柱状图颜色
            let barColor = '#667eea'; // 默认伤害颜色
            switch (displaySettings.sortBy) {
                case 'healing':
                    barColor = '#2ecc71'; // 绿色表示治疗
                    break;
                case 'taken':
                    barColor = '#e74c3c'; // 红色表示承伤
                    break;
                case 'dps':
                    barColor = '#f39c12'; // 橙色表示DPS
                    break;
                case 'hps':
                    barColor = '#27ae60'; // 深绿色表示HPS
                    break;
                default:
                    barColor = '#667eea'; // 蓝色表示伤害
                    break;
            }
            
            percentageBar.innerHTML = `<div class="percentage-fill" style="width: ${percentage}%; background-color: ${barColor};"></div>`;
            // 点击进度条区域也能展开技能详情
            percentageBar.addEventListener('click', (e) => {
                e.stopPropagation();
                const button = damageItem.querySelector('.skill-btn');
                if (button) togglePlayerSkillDetails(player.uid, button);
            });
            damageMain.appendChild(percentageBar);

            // 迷你条：治疗/承伤百分比相对所选排序最大值，便于快速对比
            const miniBars = document.createElement('div');
            miniBars.className = 'mini-bars';
            // 治疗
            if (displaySettings.showHealing && hasHealing) {
                const mini = document.createElement('div');
                mini.className = 'mini';
                mini.innerHTML = `
                    <span class="mini-label">治</span>
                    <div class="mini-bar"><div class="fill heal" style="width:${maxValue>0?Math.round(((healingData.total||0)/maxValue)*100):0}%"></div></div>
                    <span class="mini-percent">${((healingData.total||0)>0?Math.round(((healingData.total||0)/maxValue)*100):0)}%</span>
                `;
                miniBars.appendChild(mini);
            }
            // 承伤
            if (displaySettings.showTaken && takenDamage > 0) {
                const mini = document.createElement('div');
                mini.className = 'mini';
                mini.innerHTML = `
                    <span class="mini-label">承</span>
                    <div class="mini-bar"><div class="fill taken" style="width:${maxValue>0?Math.round(((takenDamage||0)/maxValue)*100):0}%"></div></div>
                    <span class="mini-percent">${((takenDamage||0)>0?Math.round(((takenDamage||0)/maxValue)*100):0)}%</span>
                `;
                miniBars.appendChild(mini);
            }
            if (miniBars.children.length>0) damageMain.appendChild(miniBars);
            
            damageItem.appendChild(damageMain);
            
            // 整个玩家条点击展开/收起技能详情
            damageItem.addEventListener('click', (e) => {
                if (settings.locked) return;
                e.stopPropagation();
                togglePlayerSkillDetailsByItem(player.uid, damageItem);
            });
            
            // 创建技能详情区域
            const skillDetails = document.createElement('div');
            skillDetails.className = 'skill-details';
            skillDetails.id = `skill-${player.uid}`;
            skillDetails.style.display = 'none';
            skillDetails.innerHTML = '<div class="skill-loading">加载技能数据中...</div>';
            
            damageItem.appendChild(skillDetails);
            
            // 添加到列表
            damageList.appendChild(damageItem);
        });
        
        // 事件委托已在初始化时绑定，无需重复绑定
        
        // 更新完成后，确保透明度正确应用到新创建的元素
        if (settings.opacity) {
            updateElementsOpacity(settings.opacity);
        }
        
    } catch (error) {
        console.error('更新显示失败:', error);
        damageList.innerHTML = `<div class="loading">❌ 连接失败: ${error.message}</div>`;
    }
}

// 直接点击处理函数（全局函数，供onclick调用）
window.handleSkillButtonDirectClick = function(uid, button) {
    console.log('直接点击处理函数被调用，UID:', uid);
    console.log('按钮元素:', button);
    console.log('锁定状态:', settings.locked);
    
    if (settings.locked) {
        console.log('窗口已锁定，无法点击');
        alert('窗口已锁定，请先解锁后再操作');
        return;
    }
    
    if (button.disabled) {
        console.log('按钮已禁用，不执行操作');
        return;
    }
    
    console.log('调用togglePlayerSkillDetails，UID:', uid);
    togglePlayerSkillDetails(uid, button);
};

// 切换玩家技能详情展开/收起
async function togglePlayerSkillDetails(uid, button) {
    console.log('togglePlayerSkillDetails调用，UID:', uid);
    
    const skillDetailsDiv = document.getElementById(`skill-${uid}`);
    if (!skillDetailsDiv) {
        alert(`❌ 错误：找不到技能详情容器\nID: skill-${uid}`);
        return;
    }
    
    const isExpanded = skillDetailsDiv.style.display !== 'none';
    console.log('当前展开状态:', isExpanded);
    
    if (isExpanded) {
        // 收起
        skillDetailsDiv.style.display = 'none';
        const damageItem = button.closest('.damage-item');
        if (damageItem) damageItem.classList.remove('expanded');
    } else {
        // 展开
        skillDetailsDiv.style.display = 'block';
        const damageItem = button.closest('.damage-item');
        if (damageItem) damageItem.classList.add('expanded');
        try { await loadPlayerSkillData(uid, skillDetailsDiv); } catch (error) { console.error('技能数据加载失败:', error); }
    }
}

// 通过玩家条 DOM 切换展开
async function togglePlayerSkillDetailsByItem(uid, damageItem) {
    const skillDetailsDiv = document.getElementById(`skill-${uid}`);
    if (!skillDetailsDiv) return;
    const isExpanded = skillDetailsDiv.style.display !== 'none';
    if (isExpanded) {
        skillDetailsDiv.style.display = 'none';
        damageItem.classList.remove('expanded');
    } else {
        skillDetailsDiv.style.display = 'block';
        damageItem.classList.add('expanded');
        try { await loadPlayerSkillData(uid, skillDetailsDiv); } catch (e) { console.error(e); }
    }
}

// 加载玩家技能数据
async function loadPlayerSkillData(uid, container) {
    console.log('加载玩家技能数据，UID:', uid);
    
    try {
        container.innerHTML = '<div class="skill-loading">🔄 加载技能数据中...</div>';
        
        // 使用已有的fetchData函数
        const response = await fetchData(`http://localhost:8989/api/skill-stats/${uid}`);
        
        if (response.code === 0 && response.data && response.data.length > 0) {
            renderSkillDetails(response.data, container, uid);
        } else {
            container.innerHTML = '<div class="skill-error">暂无技能数据</div>';
        }
    } catch (error) {
        console.error('加载技能数据时出错:', error);
        container.innerHTML = '<div class="skill-error">❌ 加载失败: ' + error.message + '</div>';
    }
}

// 渲染技能详情
function renderSkillDetails(skillData, container, uid) {
    console.log('渲染技能详情，UID:', uid, '数据:', skillData);
    
    let html = '<div class="skill-details-content">';
    html += '';

    if (skillData && skillData.length > 0) {
        // 计算最大百分比用于动画最小宽度
        skillData.forEach((skill) => {
            const percentage = Math.max(parseFloat(skill.percentage) || 0, 0);
            const name = skill.skill_name || `技能${skill.skill_id}`;
            const damage = skill.total_damage || 0;
            const count = skill.count || 0;
            html += `
                <div class="skill-item">
                    <div class="skill-line">
                        <div class="skill-col-name" title="${name}">${name}</div>
                        <div class="skill-col-damage">${formatNumber(damage)}</div>
                        <div class="skill-col-count">${count}次</div>
                        <div class="skill-col-percentage">${percentage.toFixed(1)}%</div>
                    </div>
                    <div class="skill-bar-row">
                        <div class="skill-bar-fill" style="width: ${Math.max(percentage, 2)}%;"></div>
                    </div>
                </div>
            `;
        });
    } else {
        html += '<div class="skill-empty">📭 暂无技能数据</div>';
    }

    html += '</div>';
    container.innerHTML = html;
}

// 事件绑定检查函数已不再需要，因为使用了onclick直接绑定

// 格式化数字
function formatNumber(num) {
    if (num >= 1000000) {
        return (num / 1000000).toFixed(1) + 'M';
    } else if (num >= 1000) {
        return (num / 1000).toFixed(1) + 'K';
    }
    return num.toString();
}

// 总览柱状图渲染
function updateOverviewBars(userMap) {
    try {
        const totals = { damage: 0, healing: 0, taken: 0 };
        Object.keys(userMap).forEach(uid => {
            const u = userMap[uid] || {};
            totals.damage += (u.total_damage?.total || 0);
            totals.healing += (u.total_healing?.total || 0);
            totals.taken += (u.taken_damage || 0);
        });
        const maxAll = Math.max(totals.damage, totals.healing, totals.taken, 1);
        // 总伤害
        const dmgEl = document.querySelector('#overviewDamage');
        if (dmgEl) dmgEl.textContent = formatNumber(totals.damage);
        const dmgFill = document.querySelector('.overview-fill.damage');
        if (dmgFill) dmgFill.style.width = `${Math.round((totals.damage / maxAll) * 100)}%`;
        // 总治疗
        const healEl = document.querySelector('#overviewHealing');
        if (healEl) healEl.textContent = formatNumber(totals.healing);
        const healFill = document.querySelector('.overview-fill.healing');
        if (healFill) healFill.style.width = `${Math.round((totals.healing / maxAll) * 100)}%`;
        // 总承伤
        const takenEl = document.querySelector('#overviewTaken');
        if (takenEl) takenEl.textContent = formatNumber(totals.taken);
        const takenFill = document.querySelector('.overview-fill.taken');
        if (takenFill) takenFill.style.width = `${Math.round((totals.taken / maxAll) * 100)}%`;
    } catch (e) {
        console.warn('updateOverviewBars error', e);
    }
}

// 显示错误
function showError(message) {
    const damageList = document.getElementById('damageList');
    damageList.innerHTML = `<div class="loading">❌ ${message}</div>`;
}

// 开始数据刷新
function startDataRefresh() {
    // 立即更新一次
    updateDisplay();
    
    // 清除现有定时器
    if (refreshTimer) {
        clearInterval(refreshTimer);
    }
    
    // 设置新的定时器
    refreshTimer = setInterval(updateDisplay, settings.refreshInterval);
}

// 停止数据刷新
function stopDataRefresh() {
    if (refreshTimer) {
        clearInterval(refreshTimer);
        refreshTimer = null;
    }
}

// 设置面板相关函数
function toggleSettings() {
    const panel = document.getElementById('settingsPanel');
    panel.classList.toggle('hidden');
    
    // 如果处于锁定状态，需要为设置面板添加鼠标事件
    if (settings.locked) {
        if (!panel.classList.contains('hidden')) {
            // 设置面板打开时，禁用穿透
            ipcRenderer.invoke('set-click-through', false);
            panel.addEventListener('mouseenter', handleSettingsPanelMouseEnter);
            panel.addEventListener('mouseleave', handleSettingsPanelMouseLeave);
        } else {
            // 设置面板关闭时，移除事件监听器并恢复穿透
            panel.removeEventListener('mouseenter', handleSettingsPanelMouseEnter);
            panel.removeEventListener('mouseleave', handleSettingsPanelMouseLeave);
            ipcRenderer.invoke('set-click-through', true);
        }
    }
}

function hideSettings() {
    const panel = document.getElementById('settingsPanel');
    panel.classList.add('hidden');
    
    // 如果处于锁定状态，需要恢复穿透并移除事件监听器
    if (settings.locked) {
        panel.removeEventListener('mouseenter', handleSettingsPanelMouseEnter);
        panel.removeEventListener('mouseleave', handleSettingsPanelMouseLeave);
        ipcRenderer.invoke('set-click-through', true);
    }
}

// 设置面板鼠标事件处理
function handleSettingsPanelMouseEnter() {
    if (settings.locked) {
        ipcRenderer.invoke('set-click-through', false);
    }
}

function handleSettingsPanelMouseLeave() {
    if (settings.locked) {
        ipcRenderer.invoke('set-click-through', true);
    }
}

// 计时器面板鼠标事件处理
function handleTimerPanelMouseEnter() {
    if (settings.locked) {
        ipcRenderer.invoke('set-click-through', false);
    }
}

function handleTimerPanelMouseLeave() {
    if (settings.locked) {
        ipcRenderer.invoke('set-click-through', true);
    }
}

function updateSettingsUI() {
    document.getElementById('opacitySlider').value = settings.opacity;
    document.getElementById('opacityValue').textContent = Math.round(settings.opacity * 100) + '%';
    document.getElementById('widthInput').value = settings.width;
    document.getElementById('heightInput').value = settings.height;
    document.getElementById('alwaysOnTopCheck').checked = settings.alwaysOnTop;
    document.getElementById('refreshInterval').value = settings.refreshInterval;
    // 个性化设置
    const fontSizeInput = document.getElementById('fontSizeInput');
    const themeColorInput = document.getElementById('themeColorInput');
    if (fontSizeInput) fontSizeInput.value = settings.fontSize;
    if (themeColorInput) themeColorInput.value = settings.themeColor;
    const compactCheck = document.getElementById('compactModeCheck');
    if (compactCheck) compactCheck.checked = settings.compactMode;
    const themeRadios = document.querySelectorAll('input[name="themeMode"]');
    themeRadios.forEach(r => r.checked = (r.value === settings.themeMode));
    
    // 初始化CSS透明度变量
    document.documentElement.style.setProperty('--bg-opacity', settings.opacity);
    
    // 初始化时也直接更新元素透明度
    updateElementsOpacity(settings.opacity);
    
    applyThemeToDocument();
}

// 设置更新函数
async function updateOpacity() {
    const opacity = parseFloat(document.getElementById('opacitySlider').value);
    document.getElementById('opacityValue').textContent = Math.round(opacity * 100) + '%';
    
    // 更新CSS变量，控制框体内部透明度
    document.documentElement.style.setProperty('--bg-opacity', opacity);
    console.log('🎨 透明度已更新:', opacity, '- CSS变量已设置');
    
    // 直接更新所有关键元素的透明度，确保立即生效
    updateElementsOpacity(opacity);
    
    settings.opacity = opacity;
    await ipcRenderer.invoke('update-settings', { opacity });
}

// 直接更新所有元素透明度的函数
function updateElementsOpacity(opacity) {
    console.log('🔧 直接更新元素透明度:', opacity);
    
    // 统计找到的元素数量
    const damageItems = document.querySelectorAll('.damage-item');
    const rankBadges = document.querySelectorAll('.rank-badge');
    const chips = document.querySelectorAll('.chip');
    const skillItems = document.querySelectorAll('.skill-item');
    
    console.log('📊 找到的元素:', {
        damageItems: damageItems.length,
        rankBadges: rankBadges.length,
        chips: chips.length,
        skillItems: skillItems.length
    });
    
    // 更新玩家条背景
    document.querySelectorAll('.damage-item').forEach(item => {
        if (item.classList.contains('rank-1')) {
            item.style.background = `linear-gradient(135deg, rgba(255, 206, 84, ${opacity * 0.35}) 0%, rgba(255, 255, 255, ${opacity * 0.12}) 100%)`;
        } else if (item.classList.contains('rank-2')) {
            item.style.background = `linear-gradient(135deg, rgba(192, 57, 43, ${opacity * 0.25}) 0%, rgba(255, 255, 255, ${opacity * 0.12}) 100%)`;
        } else if (item.classList.contains('rank-3')) {
            item.style.background = `linear-gradient(135deg, rgba(142, 68, 173, ${opacity * 0.25}) 0%, rgba(255, 255, 255, ${opacity * 0.12}) 100%)`;
        }
    });
    
    // 更新排行标签
    document.querySelectorAll('.rank-badge').forEach(badge => {
        badge.style.background = `rgba(255, 255, 255, ${opacity * 0.25})`;
    });
    
    // 更新芯片背景
    document.querySelectorAll('.chip').forEach(chip => {
        chip.style.background = `rgba(255, 255, 255, ${opacity * 0.1})`;
        chip.style.borderColor = `rgba(255, 255, 255, ${opacity * 0.18})`;
    });
    
    // 更新技能项背景
    document.querySelectorAll('.skill-item').forEach(item => {
        item.style.background = `rgba(255, 255, 255, ${opacity * 0.08})`;
    });
    
    // 更新技能详情容器
    document.querySelectorAll('.skill-details').forEach(details => {
        details.style.background = `rgba(0, 0, 0, ${opacity * 0.4})`;
        details.style.borderColor = `rgba(255, 206, 84, ${opacity * 0.4})`;
    });
    
    // 更新技能进度条背景
    document.querySelectorAll('.skill-bar-row').forEach(bar => {
        bar.style.background = `rgba(255, 255, 255, ${opacity * 0.12})`;
    });
    
    // 更新迷你进度条
    document.querySelectorAll('.mini-bar').forEach(bar => {
        bar.style.background = `rgba(255, 255, 255, ${opacity * 0.25})`;
    });
    
    console.log('✅ 所有元素透明度已直接更新');
}

async function updateSize() {
    const width = parseInt(document.getElementById('widthInput').value);
    const height = parseInt(document.getElementById('heightInput').value);
    
    settings.width = width;
    settings.height = height;
    await ipcRenderer.invoke('update-settings', { width, height });
}

async function updateAlwaysOnTop() {
    const alwaysOnTop = document.getElementById('alwaysOnTopCheck').checked;
    
    settings.alwaysOnTop = alwaysOnTop;
    await ipcRenderer.invoke('update-settings', { alwaysOnTop });
}

function updateRefreshInterval() {
    const interval = parseInt(document.getElementById('refreshInterval').value);
    settings.refreshInterval = interval;
    
    // 重新启动数据刷新
    startDataRefresh();
}

// 个性化：主题与字体
function applyThemeToDocument() {
    const root = document.documentElement;
    root.style.setProperty('--theme-color', settings.themeColor);
    root.style.setProperty('--font-size-base', `${settings.fontSize}px`);
    document.body.classList.toggle('compact-mode', settings.compactMode);
    document.body.classList.toggle('theme-light', settings.themeMode === 'light');
}

function updateFontSizeSetting() {
    const value = parseInt(document.getElementById('fontSizeInput').value, 10);
    if (Number.isFinite(value) && value >= 10 && value <= 20) {
        settings.fontSize = value;
        localStorage.setItem('overlay_fontSize', String(value));
        applyThemeToDocument();
    }
}

function updateThemeColorSetting() {
    const value = document.getElementById('themeColorInput').value;
    if (value) {
        settings.themeColor = value;
        localStorage.setItem('overlay_themeColor', value);
        applyThemeToDocument();
    }
}

// 紧凑模式与主题切换
function updateCompactMode() {
    const checked = document.getElementById('compactModeCheck').checked;
    settings.compactMode = checked;
    localStorage.setItem('overlay_compact', checked ? '1' : '0');
    applyThemeToDocument();
}

function updateThemeMode() {
    const checked = document.querySelector('input[name="themeMode"]:checked');
    if (checked) {
        settings.themeMode = checked.value;
        localStorage.setItem('overlay_themeMode', settings.themeMode);
        applyThemeToDocument();
    }
}

async function resetPosition() {
    const newSettings = { x: 100, y: 100 };
    settings = { ...settings, ...newSettings };
    await ipcRenderer.invoke('update-settings', newSettings);
}

// 窗口控制函数
async function minimizeWindow() {
    await ipcRenderer.invoke('minimize-app');
}

async function closeWindow() {
    stopDataRefresh();
    await ipcRenderer.invoke('close-app');
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', init);

// 页面卸载时清理资源
window.addEventListener('beforeunload', () => {
    stopDataRefresh();
    if (timerState.timerInterval) {
        clearInterval(timerState.timerInterval);
    }
});

// 计时器相关函数
function toggleTimer() {
    const panel = document.getElementById('timerPanel');
    panel.classList.toggle('hidden');
    
    // 如果处于锁定状态，需要为计时器面板添加鼠标事件
    if (settings.locked) {
        if (!panel.classList.contains('hidden')) {
            // 计时器面板打开时，禁用穿透
            ipcRenderer.invoke('set-click-through', false);
            panel.addEventListener('mouseenter', handleTimerPanelMouseEnter);
            panel.addEventListener('mouseleave', handleTimerPanelMouseLeave);
        } else {
            // 计时器面板关闭时，移除事件监听器并恢复穿透
            panel.removeEventListener('mouseenter', handleTimerPanelMouseEnter);
            panel.removeEventListener('mouseleave', handleTimerPanelMouseLeave);
            ipcRenderer.invoke('set-click-through', true);
        }
    }
    
    updateTimerDisplay();
}

function hideTimer() {
    const panel = document.getElementById('timerPanel');
    panel.classList.add('hidden');
    
    // 如果处于锁定状态，需要恢复穿透并移除事件监听器
    if (settings.locked) {
        panel.removeEventListener('mouseenter', handleTimerPanelMouseEnter);
        panel.removeEventListener('mouseleave', handleTimerPanelMouseLeave);
        ipcRenderer.invoke('set-click-through', true);
    }
}

function setTimerDuration(seconds) {
    if (!timerState.isRunning) {
        timerState.duration = seconds;
        timerState.timeLeft = seconds;
        updateTimerDisplay();
        document.getElementById('startTimerBtn').disabled = false;
        document.getElementById('timerMode').textContent = `设置${seconds}秒`;
    }
}

function startTimer() {
    if (timerState.isRunning) return;
    
    // 保存当前数据作为基准
    fetchDamageData().then(data => {
        timerState.initialData = data;
        console.log('Timer started with initial data:', data);
    }).catch(err => {
        console.log('Warning: Could not fetch initial data:', err);
        timerState.initialData = {};
    });
    
    timerState.isRunning = true;
    timerState.startTime = Date.now();
    
    // 启动计时器
    timerState.timerInterval = setInterval(() => {
        timerState.timeLeft--;
        updateTimerDisplay();
        
        if (timerState.timeLeft <= 0) {
            finishTimer();
        }
    }, 1000);
    
    // 更新UI
    document.getElementById('startTimerBtn').disabled = true;
    document.getElementById('stopTimerBtn').disabled = false;
        document.getElementById('timerStatusText').textContent = '计时中';
        document.getElementById('timerMode').textContent = '计时进行中';
    
    // 添加计时动画
        document.getElementById('timerText').parentElement.classList.add('counting');
    
    // 清理数据 - 调用服务器API
    clearServerData();
}

function stopTimer() {
    if (!timerState.isRunning) return;
    
    timerState.isRunning = false;
    
    if (timerState.timerInterval) {
        clearInterval(timerState.timerInterval);
        timerState.timerInterval = null;
    }
    
    // 更新UI
    document.getElementById('startTimerBtn').disabled = false;
    document.getElementById('stopTimerBtn').disabled = true;
        document.getElementById('timerStatusText').textContent = '已停止';
    document.getElementById('timerMode').textContent = '手动停止';
    
    // 移除动画
    document.getElementById('timerText').parentElement.classList.remove('counting');
}

function finishTimer() {
    timerState.isRunning = false;
    
    if (timerState.timerInterval) {
        clearInterval(timerState.timerInterval);
        timerState.timerInterval = null;
    }
    
    // 更新UI
    document.getElementById('startTimerBtn').disabled = false;
    document.getElementById('stopTimerBtn').disabled = true;
        document.getElementById('timerStatusText').textContent = '计时完成';
    document.getElementById('timerMode').textContent = '时间到！';
    
    // 添加完成动画
    const timerDisplay = document.getElementById('timerText').parentElement;
    timerDisplay.classList.remove('counting');
    timerDisplay.classList.add('finished');
    
    // 停止抓包 - 调用服务器API
    stopServerCapture();
    
    // 显示完成通知
    setTimeout(() => {
        alert(`计时完成！总时长：${timerState.duration}秒`);
        timerDisplay.classList.remove('finished');
    }, 1000);
}

function resetTimer() {
    if (timerState.isRunning) {
        stopTimer();
    }
    
    timerState.timeLeft = timerState.duration;
    timerState.initialData = null;
    
    updateTimerDisplay();
    document.getElementById('timerStatusText').textContent = '已重置';
    document.getElementById('timerMode').textContent = '就绪';
    
    // 重置数据 - 调用服务器API
    clearServerData();
}

function exitTimerMode() {
    if (timerState.isRunning) {
        if (confirm('计时器正在运行，确定要退出计时模式吗？')) {
            stopTimer();
        } else {
            return;
        }
    }
    
    hideTimer();
    document.getElementById('timerStatusText').textContent = '未开始';
    document.getElementById('timerMode').textContent = '就绪';
}

function updateTimerDisplay() {
    const minutes = Math.floor(timerState.timeLeft / 60);
    const seconds = timerState.timeLeft % 60;
    const timeString = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    
    document.getElementById('timerText').textContent = timeString;
}

// 服务器通信函数
async function clearServerData() {
    try {
        const response = await fetchData('http://localhost:8989/api/clear');
        console.log('Server data cleared:', response);
        document.getElementById('captureStatusText').textContent = '数据已清理';
    } catch (error) {
        console.error('Failed to clear server data:', error);
        document.getElementById('captureStatusText').textContent = '清理失败';
    }
}

// 清空服务端并刷新UI
async function clearServerDataAndUi() {
    try {
        await clearServerData();
        const damageList = document.getElementById('damageList');
        if (damageList) {
            damageList.innerHTML = '<div class="loading">🧹 已清空数据</div>';
        }
        lastDataHash = '';
        setTimeout(updateDisplay, 300);
    } catch (e) {
        console.error('清空失败:', e);
    }
}

async function stopServerCapture() {
    try {
        // 这里需要根据实际的服务器API来实现停止抓包功能
        // 目前先模拟停止功能
        console.log('Stop capture request sent');
        document.getElementById('captureStatusText').textContent = '抓包已停止';
        
        // 实际实现时，可能需要调用类似这样的API：
        // const response = await fetchData('http://localhost:8989/api/stop-capture');
    } catch (error) {
        console.error('Failed to stop capture:', error);
        document.getElementById('captureStatusText').textContent = '停止失败';
    }
}

// 排序和显示控制函数
function sortPlayers(players) {
    switch (displaySettings.sortBy) {
        case 'damage':
            players.sort((a, b) => b.total_damage.total - a.total_damage.total);
            break;
        case 'healing':
            players.sort((a, b) => {
                const aHealing = (a.total_healing && a.total_healing.total) || 0;
                const bHealing = (b.total_healing && b.total_healing.total) || 0;
                return bHealing - aHealing;
            });
            break;
        case 'dps':
            players.sort((a, b) => b.total_dps - a.total_dps);
            break;
        case 'hps':
            players.sort((a, b) => {
                const aHps = a.total_hps || 0;
                const bHps = b.total_hps || 0;
                return bHps - aHps;
            });
            break;
        case 'taken':
            players.sort((a, b) => {
                const aTaken = a.taken_damage || 0;
                const bTaken = b.taken_damage || 0;
                return bTaken - aTaken;
            });
            break;
        case 'profession':
            players.sort((a, b) => {
                const aProfession = a.profession || '未知';
                const bProfession = b.profession || '未知';
                return aProfession.localeCompare(bProfession, 'zh-CN');
            });
            break;
        default:
            players.sort((a, b) => b.total_damage.total - a.total_damage.total);
            break;
    }
}

function setSortMode(sortType) {
    displaySettings.sortBy = sortType;
    // 同步下拉单选框
    const radio = document.querySelector(`input[name="sortBy"][value="${sortType}"]`);
    if (radio) radio.checked = true;
    // 重新刷新显示
    updateDisplay();
}

// 初始化时从勾选项恢复排序
function initSortFromMenu() {
    const checked = document.querySelector('input[name="sortBy"]:checked');
    if (checked) {
        displaySettings.sortBy = checked.value;
    }
    // 重新刷新显示
    updateDisplay();
}

function updateDisplaySettings() {
    displaySettings.showDamage = document.getElementById('showDamageDropdown').checked;
    displaySettings.showHealing = document.getElementById('showHealingDropdown').checked;
    displaySettings.showTaken = document.getElementById('showTakenDropdown').checked;
    displaySettings.showProfession = document.getElementById('showProfessionDropdown').checked;
    
    // 重新刷新显示
    updateDisplay();
}

// 锁定/解锁功能
function toggleLock() {
    settings.locked = !settings.locked;
    const lockBtn = document.getElementById('lockBtn');
    const titleBar = document.getElementById('titleBar');
    const content = document.getElementById('content');
    
    if (settings.locked) {
        lockBtn.textContent = '解锁';
        lockBtn.classList.add('locked');
        lockBtn.title = '解锁位置';
        
        // 检查设置面板和计时器面板是否已打开
        const settingsPanel = document.getElementById('settingsPanel');
        const timerPanel = document.getElementById('timerPanel');
        const isSettingsOpen = settingsPanel && !settingsPanel.classList.contains('hidden');
        const isTimerOpen = timerPanel && !timerPanel.classList.contains('hidden');
        
        // 如果两个面板都没打开，则启用窗口级穿透
        if (!isSettingsOpen && !isTimerOpen) {
            ipcRenderer.invoke('set-click-through', true);
        }
        
        if (content) content.style.pointerEvents = 'auto';
        titleBar.style.pointerEvents = 'auto';
        titleBar.style.webkitAppRegion = 'no-drag';
        
        // 悬停标题栏时关闭穿透，离开时开启穿透
        titleBar.addEventListener('mousemove', handleTitleBarMouseEnterTempDisable, false);
        titleBar.addEventListener('mouseleave', handleTitleBarMouseLeaveEnable, false);
        
        // 如果设置面板已打开，为其添加鼠标事件
        if (isSettingsOpen) {
            settingsPanel.addEventListener('mouseenter', handleSettingsPanelMouseEnter);
            settingsPanel.addEventListener('mouseleave', handleSettingsPanelMouseLeave);
        }
        
        // 如果计时器面板已打开，为其添加鼠标事件
        if (isTimerOpen) {
            timerPanel.addEventListener('mouseenter', handleTimerPanelMouseEnter);
            timerPanel.addEventListener('mouseleave', handleTimerPanelMouseLeave);
        }
        
        // 禁用所有技能按钮
        document.querySelectorAll('.skill-btn').forEach(btn => {
            btn.disabled = true;
            btn.title = '窗口已锁定，请先解锁';
        });
        
        // 设置置顶
        ipcRenderer.invoke('update-settings', { alwaysOnTop: true });
    } else {
        lockBtn.textContent = '锁定';
        lockBtn.classList.remove('locked');
        lockBtn.title = '锁定位置';
        // 恢复正常点击
        if (content) content.style.pointerEvents = 'auto';
        titleBar.style.pointerEvents = 'auto';
        titleBar.style.webkitAppRegion = 'drag';
        
        // 确保窗口级穿透已关闭
        ipcRenderer.invoke('set-click-through', false);

        // 移除标题栏事件
        titleBar.removeEventListener('mousemove', handleTitleBarMouseEnterTempDisable, false);
        titleBar.removeEventListener('mouseleave', handleTitleBarMouseLeaveEnable, false);
        
        // 移除设置面板和计时器面板事件监听器
        const settingsPanel = document.getElementById('settingsPanel');
        const timerPanel = document.getElementById('timerPanel');
        if (settingsPanel) {
            settingsPanel.removeEventListener('mouseenter', handleSettingsPanelMouseEnter);
            settingsPanel.removeEventListener('mouseleave', handleSettingsPanelMouseLeave);
        }
        if (timerPanel) {
            timerPanel.removeEventListener('mouseenter', handleTimerPanelMouseEnter);
            timerPanel.removeEventListener('mouseleave', handleTimerPanelMouseLeave);
        }
        
        // 启用所有技能按钮
        document.querySelectorAll('.skill-btn').forEach(btn => {
            btn.disabled = false;
            btn.title = '查看技能统计';
        });
    }
}

// 锁定时：鼠标在标题栏或设置面板上，暂时关闭窗口穿透；离开时，恢复穿透
function handleTitleBarMouseEnterTempDisable() {
    ipcRenderer.invoke('set-click-through', false);
}
function handleTitleBarMouseLeaveEnable() {
    // 检查鼠标是否移动到设置面板或计时器面板上，如果是，则不恢复穿透
    if (settings.locked) {
        const settingsPanel = document.getElementById('settingsPanel');
        const timerPanel = document.getElementById('timerPanel');
        const isSettingsVisible = settingsPanel && !settingsPanel.classList.contains('hidden');
        const isTimerVisible = timerPanel && !timerPanel.classList.contains('hidden');
        
        if (!isSettingsVisible && !isTimerVisible) {
            ipcRenderer.invoke('set-click-through', true);
        }
    }
}

// 显示玩家技能详情页面
async function showPlayerSkillDetails(uid) {
    console.log('showPlayerSkillDetails called with uid:', uid);
    
    // 设置当前编辑的玩家UID
    currentEditingPlayerUid = uid;
    
    const mainView = document.getElementById('mainView');
    const skillView = document.getElementById('skillView');
    
    if (!mainView || !skillView) {
        console.error('找不到主视图或技能视图元素');
        return;
    }
    
    // 隐藏主视图，显示技能详情视图
    mainView.style.display = 'none';
    skillView.classList.remove('hidden');
    
    // 获取玩家信息
    const currentData = await fetchDamageData();
    const player = currentData.user[uid];
    
    if (player) {
        // 更新头部信息
        document.getElementById('skillPlayerName').textContent = `玩家_${uid}`;
        document.getElementById('skillPlayerProfession').textContent = player.profession || '未知';
        
        // 加载技能详细信息
        await loadAndDisplaySkillDetails(uid, player);
    } else {
        console.error('找不到玩家数据:', uid);
        // 显示错误信息
        document.getElementById('skillDetailsList').innerHTML = '<div class="loading">❌ 找不到玩家数据</div>';
    }
}

// 显示主视图
function showMainView() {
    const mainView = document.getElementById('mainView');
    const skillView = document.getElementById('skillView');
    
    // 显示主视图，隐藏技能详情视图
    mainView.style.display = 'block';
    skillView.classList.add('hidden');
}

// 加载并显示技能详细信息
async function loadAndDisplaySkillDetails(uid, playerData) {
    const skillDetailsList = document.getElementById('skillDetailsList');
    
    try {
        // 显示加载状态
        skillDetailsList.innerHTML = '<div class="loading">🔄 加载技能信息中...</div>';
        
        // 尝试获取技能详细统计
        const response = await fetchData(`http://localhost:8989/api/skill-stats/${uid}`);
        let skillsData = {};
        
        if (response.code === 0 && response.skills) {
            skillsData = response.skills;
        }
        
        // 生成技能详情HTML
        const html = generateSkillDetailsHTML(playerData, skillsData);
        skillDetailsList.innerHTML = html;
        
    } catch (error) {
        console.error('加载技能详细信息失败:', error);
        skillDetailsList.innerHTML = '<div class="loading">❌ 加载失败</div>';
    }
}

// 生成技能详情HTML
function generateSkillDetailsHTML(playerData, skillsData) {
    const totalDamage = playerData.total_damage.total;
    const totalHealing = playerData.total_healing ? playerData.total_healing.total : 0;
    const critRate = playerData.total_count.total > 0 ? 
        ((playerData.total_count.critical / playerData.total_count.total) * 100).toFixed(1) : '0.0';
    const luckyRate = playerData.total_count.total > 0 ? 
        ((playerData.total_count.lucky / playerData.total_count.total) * 100).toFixed(1) : '0.0';
    
    let html = `
        <div class="skill-summary">
            <div class="skill-summary-title">📊 战斗统计概览</div>
            <div class="skill-summary-stats">
                <div class="skill-summary-item">
                    <span class="skill-summary-label">总伤害</span>
                    <span class="skill-summary-value">${formatNumber(totalDamage)}</span>
                </div>
                <div class="skill-summary-item">
                    <span class="skill-summary-label">DPS</span>
                    <span class="skill-summary-value">${playerData.total_dps.toFixed(0)}</span>
                </div>
                ${totalHealing > 0 ? `
                <div class="skill-summary-item">
                    <span class="skill-summary-label">总治疗</span>
                    <span class="skill-summary-value healing-value">${formatNumber(totalHealing)}</span>
                </div>
                <div class="skill-summary-item">
                    <span class="skill-summary-label">HPS</span>
                    <span class="skill-summary-value healing-value">${(playerData.total_hps || 0).toFixed(0)}</span>
                </div>
                ` : ''}
                <div class="skill-summary-item">
                    <span class="skill-summary-label">暴击率</span>
                    <span class="skill-summary-value">${critRate}%</span>
                </div>
                <div class="skill-summary-item">
                    <span class="skill-summary-label">幸运率</span>
                    <span class="skill-summary-value">${luckyRate}%</span>
                </div>
            </div>
        </div>
    `;
    
    // 处理技能数据
    const skillsArray = Object.entries(skillsData).map(([skillId, skill]) => ({
        id: skillId,
        name: skill.name || `技能${skillId}`,
        damage: skill.total || 0,
        count: skill.count || 0,
        avgDamage: skill.count > 0 ? (skill.total / skill.count) : 0
    }));
    
    // 按伤害排序
    skillsArray.sort((a, b) => b.damage - a.damage);
    
    if (skillsArray.length > 0) {
        html += `<div class="skill-list-title">🗡️ 技能详细分析</div>`;
        
        skillsArray.slice(0, 15).forEach((skill, index) => { // 显示前15个技能
            const percentage = totalDamage > 0 ? ((skill.damage / totalDamage) * 100).toFixed(1) : '0.0';
            const borderColor = index < 3 ? ['#ffce54', '#c0392b', '#8e44ad'][index] : '#667eea';
            
            html += `
                <div class="skill-item-detail" style="border-left-color: ${borderColor}">
                    <div class="skill-item-header">
                        <div class="skill-item-name">${skill.name}</div>
                        <div class="skill-item-percentage">${percentage}%</div>
                    </div>
                    <div class="skill-item-stats">
                        <div class="skill-stat-group">
                            <div class="skill-stat">
                                <span class="skill-stat-label">总伤害</span>
                                <span class="skill-stat-value">${formatNumber(skill.damage)}</span>
                            </div>
                            <div class="skill-stat">
                                <span class="skill-stat-label">使用次数</span>
                                <span class="skill-stat-value">${skill.count}</span>
                            </div>
                            <div class="skill-stat">
                                <span class="skill-stat-label">平均伤害</span>
                                <span class="skill-stat-value">${formatNumber(skill.avgDamage)}</span>
                            </div>
                        </div>
                    </div>
                </div>
            `;
        });
    } else {
        html += '<div class="loading">📭 暂无技能数据</div>';
    }
    
    return html;
}

// 昵称编辑功能
let currentEditingPlayerUid = null;

function showNicknameEditModal() {
    console.log('显示昵称编辑弹窗');
    const modal = document.getElementById('nicknameEditModal');
    const uidElement = document.getElementById('editingPlayerUid');
    const nicknameInput = document.getElementById('nicknameInput');
    
    // 获取当前正在查看的玩家信息
    if (currentEditingPlayerUid) {
        uidElement.textContent = currentEditingPlayerUid;
        
        // 获取当前昵称并填入输入框
        let currentNickname = '';
        // 优先使用主列表中该UID的昵称
        const card = document.querySelector(`.damage-item[data-uid="${currentEditingPlayerUid}"] .player-name`);
        if (card && card.textContent) currentNickname = card.textContent.trim();
        // 回退到技能页标题
        if (!currentNickname) {
            const playerNameElement = document.getElementById('skillPlayerName');
            currentNickname = playerNameElement ? playerNameElement.textContent.trim() : '';
        }
        nicknameInput.value = currentNickname;
        
        modal.classList.remove('hidden');
        nicknameInput.focus();
        nicknameInput.select();
    }
}

function hideNicknameEditModal() {
    console.log('隐藏昵称编辑弹窗');
    const modal = document.getElementById('nicknameEditModal');
    modal.classList.add('hidden');
    
    // 清空输入框
    document.getElementById('nicknameInput').value = '';
}

async function savePlayerNickname() {
    const nicknameInput = document.getElementById('nicknameInput');
    const newNickname = nicknameInput.value.trim();
    
    if (!newNickname) {
        alert('请输入昵称');
        nicknameInput.focus();
        return;
    }
    
    if (!currentEditingPlayerUid) {
        alert('无法获取玩家ID');
        return;
    }
    
    try {
        console.log('保存昵称:', { uid: currentEditingPlayerUid, nickname: newNickname });
        
        // 发送昵称更新请求到服务器
        const postData = JSON.stringify({
            uid: currentEditingPlayerUid,
            nickname: newNickname
        });
        
        const xhr = new XMLHttpRequest();
        xhr.open('POST', 'http://localhost:8989/api/update-nickname');
        xhr.setRequestHeader('Content-Type', 'application/json');
        
        xhr.onload = function() {
            if (xhr.status >= 200 && xhr.status < 300) {
                try {
                    const response = JSON.parse(xhr.responseText);
                    if (response.code === 0 || response.success) {
                        // 更新本地显示
                        document.getElementById('skillPlayerName').textContent = newNickname;
                        hideNicknameEditModal();
                        
                        // 刷新主列表显示
                        updateDisplay();
                        
                        console.log('昵称保存成功');
                    } else {
                        alert('昵称保存失败: ' + (response.message || response.msg || '未知错误'));
                    }
                } catch (e) {
                    alert('服务器响应解析失败');
                }
            } else {
                alert('昵称保存失败: HTTP ' + xhr.status);
            }
        };
        
        xhr.onerror = function() {
            alert('网络错误，无法保存昵称');
        };
        
        xhr.send(postData);
        
    } catch (error) {
        console.error('保存昵称时出错:', error);
        alert('保存昵称时出错: ' + error.message);
    }
}

// 昵称管理功能
let allNicknames = {};
let filteredNicknames = {};

async function showNicknameManager() {
    console.log('显示昵称管理窗口');
    const modal = document.getElementById('nicknameManagerModal');
    modal.classList.remove('hidden');
    
    // 加载昵称数据
    await loadNicknames();
}

function hideNicknameManager() {
    console.log('隐藏昵称管理窗口');
    const modal = document.getElementById('nicknameManagerModal');
    modal.classList.add('hidden');
    
    // 清空搜索框
    document.getElementById('nicknameSearch').value = '';
}

async function loadNicknames() {
    try {
        const xhr = new XMLHttpRequest();
        xhr.open('GET', 'http://localhost:8989/api/nicknames');
        
        xhr.onload = function() {
            if (xhr.status >= 200 && xhr.status < 300) {
                try {
                    const response = JSON.parse(xhr.responseText);
                    if (response.code === 0) {
                        allNicknames = response.data || {};
                        filteredNicknames = {...allNicknames};
                        renderNicknamesList();
                    } else {
                        console.error('获取昵称数据失败:', response.msg);
                        showNicknamesError('获取昵称数据失败');
                    }
                } catch (e) {
                    console.error('解析昵称数据失败:', e);
                    showNicknamesError('解析数据失败');
                }
            } else {
                console.error('获取昵称数据失败: HTTP', xhr.status);
                showNicknamesError('网络请求失败');
            }
        };
        
        xhr.onerror = function() {
            console.error('获取昵称数据失败: 网络错误');
            showNicknamesError('网络连接失败');
        };
        
        xhr.send();
    } catch (error) {
        console.error('加载昵称数据时出错:', error);
        showNicknamesError('加载失败: ' + error.message);
    }
}

function renderNicknamesList() {
    const nicknamesList = document.getElementById('nicknamesList');
    
    if (Object.keys(filteredNicknames).length === 0) {
        nicknamesList.innerHTML = '<div class="loading">📭 暂无昵称数据</div>';
        return;
    }
    
    let html = '';
    Object.entries(filteredNicknames).forEach(([uid, nickname]) => {
        html += `
            <div class="nickname-item" data-uid="${uid}">
                <div class="nickname-info">
                    <div class="nickname-uid">玩家ID: ${uid}</div>
                    <div class="nickname-name">${nickname}</div>
                </div>
                <div class="nickname-actions-item">
                    <button class="edit-nickname-item" data-uid="${uid}" data-nickname="${nickname.replace(/'/g, "\\'")}">✏️ 编辑</button>
                    <button class="delete-nickname-item" data-uid="${uid}">🗑️ 删除</button>
                </div>
            </div>
        `;
    });
    
    nicknamesList.innerHTML = html;
    
    // 为动态生成的按钮添加事件监听器
    document.querySelectorAll('.edit-nickname-item').forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            const uid = this.dataset.uid;
            const nickname = this.dataset.nickname;

            handleEditNickname(uid, nickname);
        });
    });
    
    document.querySelectorAll('.delete-nickname-item').forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            const uid = this.dataset.uid;

            handleDeleteNickname(uid);
        });
    });
}

// 昵称管理事件处理函数已改为onclick直接绑定，不再需要事件委托

function showNicknamesError(message) {
    const nicknamesList = document.getElementById('nicknamesList');
    nicknamesList.innerHTML = `<div class="loading">❌ ${message}</div>`;
}

function filterNicknames() {
    const searchTerm = document.getElementById('nicknameSearch').value.toLowerCase();
    
    if (!searchTerm) {
        filteredNicknames = {...allNicknames};
    } else {
        filteredNicknames = {};
        Object.entries(allNicknames).forEach(([uid, nickname]) => {
            if (uid.toLowerCase().includes(searchTerm) || 
                nickname.toLowerCase().includes(searchTerm)) {
                filteredNicknames[uid] = nickname;
            }
        });
    }
    
    renderNicknamesList();
}

async function refreshNicknamesList() {
    document.getElementById('nicknamesList').innerHTML = '<div class="loading">🔄 刷新中...</div>';
    await loadNicknames();
}

function showAddNicknameDialog() {
    // 使用自定义对话框而不是prompt
    const modal = document.createElement('div');
    modal.style.cssText = `
        position: fixed; top: 0; left: 0; width: 100%; height: 100%;
        background: rgba(0,0,0,0.8); display: flex; justify-content: center;
        align-items: center; z-index: 10000;
    `;
    
    const dialog = document.createElement('div');
    dialog.style.cssText = `
        background: #2c3e50; padding: 20px; border-radius: 8px; border: 2px solid #ffce54;
        max-width: 300px; width: 90%;
    `;
    
    dialog.innerHTML = `
        <h3 style="color: #ffce54; margin: 0 0 15px 0;">添加新昵称</h3>
        <input type="text" id="uidInput" placeholder="请输入玩家ID" 
               style="width: 100%; padding: 8px; margin-bottom: 10px; border: 1px solid #ccc; border-radius: 4px;">
        <input type="text" id="nicknameInput" placeholder="请输入昵称" 
               style="width: 100%; padding: 8px; margin-bottom: 15px; border: 1px solid #ccc; border-radius: 4px;">
        <div style="text-align: right;">
            <button id="cancelAdd" style="margin-right: 10px; padding: 6px 12px; background: #95a5a6; color: white; border: none; border-radius: 4px; cursor: pointer;">取消</button>
            <button id="saveAdd" style="padding: 6px 12px; background: #e74c3c; color: white; border: none; border-radius: 4px; cursor: pointer;">添加</button>
        </div>
    `;
    
    modal.appendChild(dialog);
    document.body.appendChild(modal);
    
    // 焦点到输入框
    const uidInput = dialog.querySelector('#uidInput');
    const nicknameInput = dialog.querySelector('#nicknameInput');
    uidInput.focus();
    
    // 事件处理
    dialog.querySelector('#saveAdd').onclick = () => {
        const uid = uidInput.value.trim();
        const nickname = nicknameInput.value.trim();
        if (uid && nickname) {
            saveNicknameInManager(uid, nickname);
        }
        document.body.removeChild(modal);
    };
    
    dialog.querySelector('#cancelAdd').onclick = () => {
        document.body.removeChild(modal);
    };
    
    // 键盘处理
    [uidInput, nicknameInput].forEach(input => {
        input.onkeydown = (e) => {
            if (e.key === 'Enter') {
                dialog.querySelector('#saveAdd').click();
            } else if (e.key === 'Escape') {
                dialog.querySelector('#cancelAdd').click();
            }
        };
    });
}

async function saveNicknameInManager(uid, nickname) {
    try {
        const xhr = new XMLHttpRequest();
        xhr.open('POST', 'http://localhost:8989/api/update-nickname');
        xhr.setRequestHeader('Content-Type', 'application/json');
        
        xhr.onload = function() {
            if (xhr.status >= 200 && xhr.status < 300) {
                try {
                    const response = JSON.parse(xhr.responseText);
                    if (response.code === 0 || response.success) {
                        console.log('昵称保存成功');
                        allNicknames[uid] = nickname;
                        filterNicknames(); // 重新渲染列表
                        updateDisplay(); // 更新主界面
                    } else {
                        alert('保存失败: ' + (response.message || response.msg || '未知错误'));
                    }
                } catch (e) {
                    alert('服务器响应解析失败');
                }
            } else {
                alert('保存失败: HTTP ' + xhr.status);
            }
        };
        
        xhr.onerror = function() {
            alert('网络错误，无法保存昵称');
        };
        
        const postData = JSON.stringify({ uid, nickname });
        xhr.send(postData);
    } catch (error) {
        console.error('保存昵称时出错:', error);
        alert('保存昵称时出错: ' + error.message);
    }
}

// 这些函数已被全局onclick函数替代

// 昵称管理的全局点击处理函数
window.handleEditNickname = function(uid, currentNickname) {
    console.log('编辑昵称被点击，UID:', uid, '当前昵称:', currentNickname);
    // 使用新的弹窗编辑方式
    currentEditingPlayerUid = uid;
    showNicknameEditModal();
};

window.handleDeleteNickname = function(uid) {
    console.log('删除昵称被点击，UID:', uid);
    if (!confirm(`确定要删除玩家ID ${uid} 的昵称吗？`)) return;
    
    // 删除昵称就是设置为空字符串
    saveNicknameInManager(uid, '').then(() => {
        delete allNicknames[uid];
        filterNicknames();
        updateDisplay();
    });
};

// 修复其他按钮的点击问题
window.handleManageNicknames = function() {
    console.log('管理昵称按钮被点击');
    showNicknameManager();
};

window.handleRefreshNicknames = function() {
    console.log('刷新昵称按钮被点击');
    refreshNicknamesList();
};

window.handleAddNickname = function() {
    console.log('添加昵称按钮被点击');
    showAddNicknameDialog();
};

window.handleCloseNicknameManager = function() {
    console.log('关闭昵称管理被点击');
    hideNicknameManager();
};

// 应用启动时初始化
document.addEventListener('DOMContentLoaded', init);
